// pages/book/index.js
const app = getApp();

Page({

  /**
   * 页面的初始数据
   */
  data: {
    course: null,
    amount: 1,
    sumPrice: 0.0,
    order: null
  },

  plusAmount() {
    let plus = this.data.order.amount + 1;
    this.setData({
      ["order.amount"]: plus,
      ["order.sumPrice"]: this.data.course.price * plus,
    });

  },

  decreaseAmount() {
    let decrease = this.data.order.amount;
    if (decrease <= 1)
      decrease = 1;
    else
      decrease--;

    this.setData({
      ["order.amount"]: decrease,
      ["order.sumPrice"]: this.data.course.price * decrease,
    });
  },

  showPayDlg(orderNu, sumPrice) {
    var that = this;
    var total_fee = sumPrice;
    total_fee = (parseFloat(total_fee) * 100).toFixed();
    console.log(total_fee, total_fee);

    wx.request({
      url: app.globalData.serverUrl + "/payment/getPaySign",
      data: {
        body: this.data.course.name,
        out_trade_no: orderNu,
        total_fee: total_fee,
        openid: app.globalData.openid
      },
      success(resp) {
        if (resp.data.success) {
          wx.requestPayment({
            'timeStamp': resp.data.data.timeStamp,
            'nonceStr': resp.data.data.nonceStr,
            'package': resp.data.data.package,
            'signType': 'MD5',
            'paySign': resp.data.sign,
            'success': function (res) {
              console.log(res);

              wx.showToast({
                icon: 'none',
                title: '支付成功',
              });

              wx.navigateTo({
                url: '../order/index',
              });
              
            },
            'fail': function (res) {
              console.log(res);
            }
          });
        } else {
          wx.showToast({
            icon: 'none',
            title: resp.data.errorMsg,
          })
        }
      },
      fail(resp) {
        console.log(resp);
      }
    });
  },

  weixpay(e) {
    let that = this;

    let obj = this.data.order;
    obj.type = this.data.course.courseType;
    obj.employeeId = app.globalData.employeeId;
    if (obj.employeeId == null) {
      wx.navigateTo({
        url: '../register/index',
      })
      return;
    }

    let orderDetailList = [];
    let obj2 = {};
    obj2.merchandiseId = this.data.course.id;
    obj2.name = this.data.course.name;
    obj2.price = this.data.course.price;
    obj2.amount = this.data.order.amount
    obj2.sumPrice = this.data.order.sumPrice;
    orderDetailList.push(obj2);

    obj.sumPrice = obj2.sumPrice;

    obj.orderDetail = orderDetailList;

    wx.showLoading({
      title: '加载中...',
    });
    wx.request({
      method: "POST",
      url: app.globalData.serverUrl + "/order/create",
      data: obj,
      success(resp) {
        wx.hideLoading();
        if (resp.data.success) {
          that.showPayDlg(resp.data.data.id, obj2.sumPrice);

        } else {
          wx.showToast({
            icon: 'none',
            title: resp.data.errorMsg,
          });
        }
      },
      fail(resp) {
        wx.hideLoading();
        wx.showToast({
          icon: 'none',
          title: JSON.stringify(resp)
        });
      }
    });
  },

  onDelayRun(a, b) {
    this.setData({
      ["order.sumPrice"]: a,
      ["order.amount"]: b,
    });
  },

  amountOnChange: function (e) {
    console.log(e.detail);

    let a = parseInt(e.detail.value);
    if (isNaN(a))
      a = 1;
    let b = this.data.course.price;
    let c = a * b;

    // setTimeout(this.onDelayRun, 2000, c, a);
    console.log(this.data.order);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;
    if (options.course != null) {
      this.setData({
        course: JSON.parse(options.course)
      });
    }

    console.log(this.data.course);

    wx.chooseAddress({
      success(obj) {
        console.log(obj);

        that.setData({
          ["order.sumPrice"]: that.data.course == null ? "0" : that.data.course.price,
          ["order.amount"] : 1,
          ["order.userName"]: obj.userName,
          ["order.telNumber"]: obj.telNumber,
          ["order.provinceCityCounty"]: obj.provinceName + " - " + obj.cityName + " - " + obj.countyName,
          ["order.detailInfo"]: obj.detailInfo,
          ["order.postalCode"]: obj.postalCode,
          ["order.remarks"]: "",
        });
      },
      fail(error) {
        console.log(error);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})